package php.code;

import com.google.common.base.Joiner;
import php.code.indentation.Indentable;
import php.code.instructions.Instruction;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public final class Sequence extends Indentable {
    private String separator = "\n";

    public final ArrayList<Indentable> elements = new ArrayList<>();

    public Sequence(Indentable parent, Instruction... instructions){
        this(parent, Arrays.asList(instructions));
    }

    protected Sequence(Indentable parent, List<Instruction> instructions) {
        super(parent);
        this.elements.addAll(instructions);
    }

    public Sequence() {
    }

    public Sequence separator(String separator) {
        this.separator = separator;

        return this;
    }

    public <T extends Indentable> T add(T indentable) {
        elements.add(indentable);
        indentable.setIndentation(getIndentation());
        indentationProperty.addListener((observable, oldValue, newValue) -> indentable.setIndentation(newValue));
        return indentable;
    }

    public Literal createLiteral(String format, Object... args) {
        return add(new Literal(format, args));
    }

    public void createLiterals(String... lines) {
        for (String line : lines)
            createLiteral(line);
    }

    @Override
    public String toString() {
        String string = Joiner
                .on(separator)
                .skipNulls()
                .join(elements);

        return string.length() == 0 ? getIndentation().toString() : string;
    }
}
